﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BLL;

public partial class CardCenter_OnlinePurchaseCardStep4 : System.Web.UI.Page
{
    DataTable shoppingCat = null;
    private BLL.PaymentBean payBean;//包装支付接口信息
    private BLL.GetPaymentAccount getAccount;//获取支付接口信息

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //获取支付结果数据
            string billNO = Request.QueryString["BillNo"].ToString();//用户支付订单号
            string realAmount = Request.QueryString["RealAmount"].ToString(); //实际扣款金额
            string billAmount = Request.QueryString["BillAmount"].ToString();//应付金额,即订单金额
            string succ = Request.QueryString["SUCC"].ToString();//支付结果
            string msg = Request.QueryString["Msg"].ToString();//支付接口返回消息
            string lhBillNo = Request.QueryString["LhBillNo"].ToString();//商户支付平台的订单号，供查账使用 
            string signMD5 = Request.QueryString["SignMD5"].ToString();//返回加密字符串

            //判断支付是否成功
            if (!string.IsNullOrEmpty(succ))
            {
                if (succ == "Y")
                {
                    //创建对账数据
                    this.InsertReconciliation(billNO, realAmount, lhBillNo);
                    if (Session["ShoppingCat"] != null && Session["payName"] != null)
                    {
                        string buyConfig = Session["BuyConfig"].ToString();
                        //控制显示哪一种操作 
                        this.HiddenBuyType.Value = buyConfig;
                        //获取支付名称
                        shoppingCat = (DataTable)Session["ShoppingCat"];
                        string payName = Session["payName"].ToString();
                        this.PaySuccess(billNO, payName);
                        Session.Remove("ShoppingCat");
                    }
                    else
                    {
                        Response.Redirect("OnlinePurchaseCardStep1.aspx");
                    }
                }
                //-------------支付失败--------------------
                else
                {
                    Response.Redirect("OnlinePurchaseCardStep4Failed.aspx");
                }
            }
        }
    }

    /// <summary>
    /// 创建对账数据
    /// </summary>
    /// <param name="userBillNo">用户支付订单号</param>
    /// <param name="realAmount">扣款金额</param>
    /// <param name="merBillNo">商户支付订单号</param>
    /// <returns>操作值</returns>
    public int InsertReconciliation(string userBillNo, string realAmount, string merBillNo)
    {
        BLL.Reconciliation reco = new Reconciliation();
        int k = 0;
        if (!string.IsNullOrEmpty(userBillNo) && !string.IsNullOrEmpty(realAmount) && string.IsNullOrEmpty(merBillNo))
        {
            k = reco.createReconciliation(userBillNo, realAmount, merBillNo);
        }
        return k;
    }


    /// <summary>
    /// 支付成功插入数据
    /// </summary>
    /// <returns></returns>
    private void PaySuccess(string parSerialNumber, string payType)
    {
        BLL.OnLinePurchaseCard parCards = new OnLinePurchaseCard();
        string smsInfo = "";
        //构建购物车中的卡的列表
        List<PurchaseCardBean> cardList = new List<PurchaseCardBean>();
        //生成咨询卡类别
        int purchaseCardType = 1;
        PurchaseCardBean bean = null;
        int k = shoppingCat.Rows.Count;
        //遍历DataTable
        for (int j = 0; j < k; j++)
        {
            string cardPoint = shoppingCat.Rows[j]["Points"].ToString();
            string mobile = shoppingCat.Rows[j]["Mobile"].ToString();
            string price = shoppingCat.Rows[j]["PerPrice"].ToString();
            int _perPrice = 0;
            int _cardPoint = 0;

            if (!string.IsNullOrEmpty(price))
            {
                _perPrice = Convert.ToInt32(price);
            }

            if (!string.IsNullOrEmpty(cardPoint))
            {
                _cardPoint = Convert.ToInt32(cardPoint);
            }

            //获取DataTable当前行类别卡的购买张数，分别构建多张卡
            string cardNums = shoppingCat.Rows[j]["CardNums"].ToString();
            int currentNums = 0;
            if (!string.IsNullOrEmpty(cardNums))
            {
                currentNums = Convert.ToInt32(cardNums);
                //构建多张当前行类别的卡
                for (int z = 0; z < currentNums; z++)
                {
                    bean = new PurchaseCardBean();
                    bean.CardPoint = _cardPoint;
                    bean.CardType = purchaseCardType;
                    bean.PaySerialNumber = parSerialNumber;
                    bean.Mobile = mobile;
                    bean.PayMoney = _perPrice;
                    bean.PayType = payType;

                    //把该卡加入到列表中
                    cardList.Add(bean);
                }
            }
        }
        //-----------------------------------------------
        //返回卡号列表
        List<string> cardNoList = new List<string>();
        //购买成功后向数据库插入数据
        string cardNo = "";
        for (int i = 0; i < cardList.Count; i++)
        {
            cardNo = parCards.OnlinePaymentAccomplished(cardList[i]);
            cardNoList.Add(cardNo);
        }
        //获取购卡信息
        BLL.CardsInfo cardinfo = new BLL.CardsInfo();
        //构造卡的数组用于根据卡号获取卡购买的信息
        Cards[] card = cardinfo.GetMultipleCardsInfo(cardNoList);

        //------ 读取用户购卡前选择------------------
        // BuyConfig : buyToCharge[购卡后充值],buyToSendSms[购卡后发送短信],buyToMergrCard[购卡后并卡]
        if (Session["BuyConfig"] != null)
        {
            string buyConfig = Session["BuyConfig"].ToString();
            if (buyConfig.Equals("2"))
            {
                Session["Cards"] = card;
                //跳转到帐户充值界面
              //  Response.Redirect("ChargetoAccount.aspx");
            }
            else if (buyConfig.Equals("1"))
            {
                Session["Cards"] = card;
                //跳转到并卡界面[新]
              //  Response.Redirect("ChargetoCard.aspx");
            }
            else
            {
                //-------------------------------------------
                //读取购卡短信模板内容
                BLL.ReadParamtes read = new ReadParamtes();
                string smsHeader = read.getParamValue("SmsPurchaseHeader");
                string smsTemplate = read.getParamValue("OnlinePurchaseCards");
                //发送短信
                BLL.SendSMS sendSms = new SendSMS();
                smsHeader = WebUtility.GenratePurchaseCarsHeaderSms(card.Length, smsHeader);
                sendSms.SendMsg(smsHeader, card[0].Mobile, "1");
                smsInfo = card.Length.ToString();
                string sms = "";
                for (int i = 0; i < card.Length; i++)
                {
                    sms = WebUtility.GenratePurchaseCardSmsText(card[i].CardSeriaNumber, card[i].CardPassword, card[i].CardPoint, smsTemplate);
                    sendSms.SendMsg(sms, card[i].Mobile, "1");
                }
                this.Lbl_PaySuccess.Text = smsInfo;
                //------------------------------
            }
        }
    }

    //--------------------------------------------
    /// <summary>
    /// 把List转换为数组
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
    private PurchaseCardBean[] transList2Array(List<PurchaseCardBean> list)
    {
        PurchaseCardBean[] beans = null;
        if (list != null)
        {
            beans = new PurchaseCardBean[list.Count];
            for (int k = 0; k < list.Count; k++)
            {
                beans[k] = list[k];
            }
        }

        return beans;
    }
    //-------------------- 
    

    protected void ChargetoCard_Click(object sender, EventArgs e)
    {
        Response.Redirect("ChargetoCard.aspx");
    }

    
	protected void ChargetoAccount_Click(object sender, EventArgs e)
    {
        Response.Redirect("ChargetoAccount.aspx");
    }
    
}
